<template>
  <div class="cart">
    <nav>
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <router-link to="/cart">购物车({{ cartItemCount }})</router-link>
    </nav>
    
    <h1>购物车</h1>
    <div v-if="cartItems.length === 0">购物车为空</div>
    <div v-else>
      <div v-for="item in cartItems" :key="item.product.id" class="cart-item">
        <span>{{ item.product.name }}</span>
        <span>¥{{ item.product.price }}</span>
        <span>
          数量: {{ item.quantity }}
          <button @click="decrementQuantity(item.product.id)">-</button>
          <button @click="incrementQuantity(item.product.id)">+</button>
        </span>
        <button @click="removeFromCart(item.product.id)">删除</button>
      </div>
      <div class="total">总价: ¥{{ cartTotal }}</div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  computed: {
    ...mapGetters(['cartItems', 'cartTotal']),
    cartItemCount() {
      return this.cartItems.reduce((count, item) => count + item.quantity, 0)
    }
  },
  methods: {
    ...mapActions([
      'incrementQuantity',
      'decrementQuantity',
      'removeFromCart'
    ])
  }
}
</script>

<style>
.cart-item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  margin: 10px;
  border: 1px solid #eee;
}
.total {
  font-weight: bold;
  margin-top: 20px;
  font-size: 1.2em;
}
button {
  margin: 0 5px;
  padding: 2px 8px;
}
</style>